package com.ming.attendance.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ming.attendance.mapper.Authorization;
import com.ming.attendance.po.ResponseBean;
import com.ming.attendance.utils.DecryptUtil;
import com.ming.attendance.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/TestController")
public class TestController {

    @Autowired
    private Authorization author;

    //login
    @GetMapping("/login")
    public ResponseBean<Map<String, String>> login(String code){
        System.out.println("code:"+code);

        String url = "https://api.weixin.qq.com/sns/jscode2session";

        Map paramMap = new HashMap<String,String>();
        paramMap.put("appid",author.getAppId());
        paramMap.put("secret",author.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");

        String result = HttpClientUtil.doGet(url, paramMap);

        JSONObject jsonObject = JSON.parseObject(result);
        String session_key = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        System.out.println("session_key: "+session_key);
        System.out.println("openid: "+openid);

        StaticVariable.session_key = session_key;
        StaticVariable.openid = openid;

        Map<String, String> returnData = new HashMap<>();
        returnData.put("openid",openid);
        return new ResponseBean<>(returnData);
    }

    @GetMapping("/getWeRunData")
    public ResponseBean<Object> getWeRunData(String encryptedData,String iv){
        String result = DecryptUtil.decryptWxDataOfHutool(encryptedData, StaticVariable.session_key, iv);
        System.out.println("getWeRunData:"+result);
        return new ResponseBean<>(JSON.parse(result));
    }

    @PostMapping("/getGroupEnterInfo")
    public ResponseBean<Object> getGroupEnterInfo(String encryptedData,String iv){

        System.out.println("encryptedData: >>>>> " + encryptedData);
        System.out.println("iv: >>>>> " + iv);
        System.out.println("session_key: >>>>> " + StaticVariable.session_key);
        String result = DecryptUtil.decryptWxDataOfHutool(encryptedData, StaticVariable.session_key, iv);

        System.out.println("解密结果: >>>>>>  "+result);
        return new ResponseBean<>(JSON.parse(result));
    }

    public static class StaticVariable {
        static String session_key;
        static String openid;
    }
}
